//
//  main.c
//  Thread
//
//  Created by wangrui on 15/4/15.
//  Copyright (c) 2015年 PPS. All rights reserved.
//

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void * do_stuff(void *param) {
    long thead_no = (long)param;
    printf("Thread number %ld \n",thead_no);
    
    sleep(10);
    
    return (void *)(thead_no + 1);
}

pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER;
long beers = 100000;

void * drink_lots(void *a) {
    
    int i;
    
    pthread_mutex_lock(&beers_lock);
    
    for (i = 0; i<10000; i++) {
        beers -= 1;
    }
    
    pthread_mutex_unlock(&beers_lock);
    
    printf("beers = %li\n",beers);
    
    return NULL;
}

int main(int argc, const char * argv[]) {
   
    pthread_t threads[20];
    
    long t;
    for (t=0; t<3; t++) {
        pthread_create(&threads[t], NULL, drink_lots, (void *)t);
    }
    
    void *result;
    for (t=0; t<3; t++) {
        pthread_join(threads[t], &result);//等待线程完成
        printf("Thread %ld return %ld \n",t,(long)result);
    }
    
    return 0;
}
